package com.jing.yao.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jing.yao.cache.CacheHelper;
import com.jing.yao.component.mapper.injected.YaoSqlInjector;
import com.jing.yao.config.converter.YaoJacksonMessageConverter;
import com.jing.yao.config.filter.I18nFilter;
import com.jing.yao.i18.MessageSourceHolder;
import com.jing.yao.utils.ApplicationContextUtils;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

/**
 * 将一些通用的Bean注入到Spring中
 * @author lirui
 * @since 2020-06-20
 */
public class BaseConfigurationBean {

    /**
     * 生成各代码编号，如：服务代码，仓库代码
     * @return
     */
    @Bean
    public GeneratorSerialNumber generatorSerialNumber() {
        return new GeneratorSerialNumber();
    }

    /**
     * 缓存帮助类
     * @return
     */
    @Bean
    public CacheHelper cacheHelper() {
        return new CacheHelper();
    }

    /**
     * 国际化
     * @return
     */
    @Bean
    public MessageSourceHolder messageSourceHolder() {
        return new MessageSourceHolder();
    }

    /**
     * 乐观锁，需要在version字段上加@Version
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * 填充sql
     * @return
     */
    @Bean
    public YaoSqlInjector customSqlInjector() {
        return new YaoSqlInjector();
    }

    /**
     * 分页
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 注册过滤器，把时区放入ThreadLocal，让当前所有方法能共享
     * @return
     */
    @Bean
    public FilterRegistrationBean i18nFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new I18nFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.setName("i18nFilter");
        registrationBean.setOrder(0);
        return registrationBean;
    }

    /**
     * 国际化日期灵活改变
     * @param objectMapper
     * @return
     */
    @Bean
    public YaoJacksonMessageConverter customJacksonMessageConverter(ObjectMapper objectMapper) {
        return new YaoJacksonMessageConverter(objectMapper);
    }

    @Bean
    public CustomWebMvcConfigurer customWebMvcConfigurer() {
        return new CustomWebMvcConfigurer();
    }

    /**
     * 默认填充
     * @return
     */
    @Bean
    public MybatisPlusMetaObjectHandler mybatisPlusMetaObjectHandler(){
        return new MybatisPlusMetaObjectHandler();
    }

    /**
     * spring上下文工具类
     * @return
     */
    @Bean
    public ApplicationContextUtils applicationContextUtils() {
        return new ApplicationContextUtils();
    }
}
